package br.ufc.si.DAO;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.caelum.vraptor.ioc.Component;
import br.ufc.si.Interfaces.IAlunoDAO;
import br.ufc.si.model.Aluno;
import br.ufc.si.util.HibernateUtil;

@Component
public class AlunoDAO implements IAlunoDAO {

	public void save(Aluno aluno) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();

		try { 
			session.save(aluno);
			t.commit();
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			session.close();
		}
	}

	public void delete(Aluno aluno) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();

		try {
			session.delete(aluno);
			t.commit();
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			session.close();
		}
	}

	public void update(Aluno aluno) {
		Session session = HibernateUtil.getSession();
		Transaction t = session.beginTransaction();

		try {
			session.update(aluno);
			t.commit();
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			session.close();
		}
	}

	@SuppressWarnings("unchecked")
	public List<Aluno> listAll() {
		Session session = HibernateUtil.getSession();
		try {
			Criteria criteria = session.createCriteria(Aluno.class);
			return criteria.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Aluno getAlunoById(Integer id) {

		Session sessao = HibernateUtil.getSession();

		try {
			return (Aluno) sessao.get(Aluno.class, id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
